// Assumes jQuery libraries already loaded
function InstallFunction(obj,functionName)
{
  obj[functionName] = function() { Request(functionName,arguments,'/rpc'); }
}

var server = {};
InstallFunction(server,'getHelpTopic');
InstallFunction(server,'getEndeavorDisplay');
InstallFunction(server,'AddUsage');
InstallFunction(server,'search');
InstallFunction(server,'getCollection');
InstallFunction(server,'getEndeavorsByConcepts');
InstallFunction(server,'getEndeavorsByTitles');
InstallFunction(server,'getEndeavorsByAlpha');

function add_use(endeavor_key)
{
  server.AddUsage(endeavor_key);
}


function CloseHelp()
{
  $("#id-howdoi-answer-div").html('');
}

function DisplayCollection(filter)
{
 $("#popular-div").css("visibility", "hidden");
 $("#subjects-div").css("visibility", "hidden");
 $("#titles-div").css("visibility", "hidden");
  Loading();
  server.getCollection(filter,DisplayCollectionSuccess);
}

function DisplayCollectionSuccess(response)
{
  if(response)
  {
   var output_str = '';
   var collection = response['collection'];
   $("#main h3").html(collection.length + " Results for <i>" + response['filter_type'] + "</i>")
   for(var i=0;i < collection.length;i++)
   {
     var endeavor = response['collection'][i];
	 output_str += GenerateRecordDisplay(endeavor);
   }
   $("#main-display-div").html(output_str);
  } else {
   $("#main h3").html("ERROR");
   $("#main-display-div").html("Could not display results");
  }
}


function DisplayEndeavor(endeavor_key)
{
 $("#popular-div").css("visibility", "hidden");
 $("#subjects-div").css("visibility", "hidden");
 $("#titles-div").css("visibility", "hidden");
 Loading();
 server.getEndeavorDisplay(endeavor_key,DisplayEndeavorSuccess);
}

function DisplayEndeavorSuccess(response)
{
 if(response)
 {
   $("#main h3").html("Details for " + response['titleInfo']['display_form']);
   var output_str = '<div class="res-detail"><b>Description:</b><p>' + response['description'] + '</p>';
   output_str += '<p>' + response['titleInfo']['display_form'];
   if(response['is_trial'])
   {
     output_str += ' is on a trial subscription. Please contact the library at <a href="mailto:library@western.edu">library@western.edu</a>';
	 output_str += ' or at 970-943-2103 to comment if we should consider purchasing for the library';
   }
   if(response['is_subscription'])
   {
     output_str += " is a subscription resource purchased for your research use."
   } else if(response['is_trial']) {
     output_str += "";
   } else {
    output_str += " is freely available and has been evaluated for your research use by librarians."
   }
   output_str += "</p></div>";
   if(response['other_publisher_resources'].length > 0)
   {
     output_str += '<div class="other-pubs">';
	 output_str += '<div id="subtitle">Other resources by ' + response['publisher_name'] + '</div>';
     for(var i=0;i < response['other_publisher_resources'].length;i++)
	 {
	   output_str += '<a href="#" onclick="DisplayEndeavor(' + "'" + response['other_publisher_resources'][i]['endeavor_key'] + "');" +'">';
	   output_str += response['other_publisher_resources'][i]['display_form'] + "</a><br/>";
	 }
	 output_str += "</div>";
   }
   output_str += '<p class="res-detail"><b>Subjects:</b><br/></td></tr><tr><td valign="top">';
   for(var i=0;i<response['concepts'].length;i++)
   {
      var subject = response['concepts'][i]['display_form'];
	  output_str += '<a href="#" onclick="DisplayCollection(\'' + subject + '\')">' + subject + '</a><br/>';
   }
   output_str += '<p class="res-detail"><b>Primary URL:</b> <a href="' + response['access_url'] + '">' + response['access_url'] + "</a><br/>";
   if(response['proxy_url']){
     output_str += '<b>Off-campus Access URL:</b> <a href="' + response['proxy_url'] + '">' + response['proxy_url'] + "</a>";
   }

   $("#main-display-div").html(output_str);
 } else {
   alert("Could not display Resource");
 }
}

function GenerateRecordDisplay(endeavor)
{
  var output = '<div class="search-result">';
  output += '<label class="dsply" property="mods:titleInfo">' + endeavor['title'] + "</label><br/>";
  output += '<label class="dsply">Description</label><div class="dsply">';
  output += endeavor['description'] + '</div>';
  output += '<label class="dsply">Access Link:</label><div class="dsply"><a href="' + endeavor['url'] + '">' + endeavor['url'] + '</a></div>';
  if(endeavor['proxy_url'])
  {
    output += '<label class="dsply">Off-campus Access URL:</label><div class="dsply"><a href="' + endeavor['proxy_url'] + '">' + endeavor['proxy_url'] + '</a></div>';
  }
  output += '<label class="dsply">Is Subscription?</label><div class="dsply">';
  if(endeavor['is_subscription'])
  {
    output += 'Yes</div>';
  } else {
    output += 'No</div>';
  }
  output += '<a href="#" onclick="DisplayEndeavor(\'' + endeavor['key'] + '\')">More information...</a></div><br/>';
  return output;
}

function GenerateSubTree(endeavor)
{
  var output = '<ul><li class="closed"><span about="/endeavor/' + endeavor['key'] + '">';
  output += '<span class="folder" property="mods:titleInfo"><a onclick="add_use(\'' + endeavor['key'];
  output += '\')" href="' + endeavor['external_url'] + '" target="_top">' + endeavor['display_form'] + '</a>';
  output += '<sup><a href="#" onclick="DisplayEndeavor(\'' + endeavor['key'] + '\')">?</a></sup></span>';
  output += '<ul><li><span class="file"><div class="record_display"><label class="dsply">Is purchased?</label><div class="dsply">';
  if(endeavor['is_subscription']) { output += 'Yes'; } else { output += 'No'; }
  output += '</div><br/><label class="dsply">Access link:</label>';
  output += '<div class="dsply" property="mods:url"><a onclick="add_use(\'' + endeavor['key'] + '\')';
  output += ' href="' + endeavor['external_url'] + '" target="_top">' + endeavor['external_url'] + '</a></div>';
  output += '<label class="dsply">Description:</label><div class="dsply" property="mods:note">' + endeavor['description'];
  output += '</div></div></li></ul></li></ul>';
  return output;
}

function GetHelpTopic()
{
 $("#popular-div").css("visibility", "hidden");
 $("#subjects-div").css("visibility", "hidden");
 $("#titles-div").css("visibility", "hidden");
 Loading();
 var help_key = $("#id-howdoi-select").attr('value');
 //$("#main-display-div").html('');
 server.getHelpTopic(help_key,GetHelpTopicSuccess);
}

function GetHelpTopicSuccess(response)
{
  if(response)
  {
    $("#main h3").html('How do I ' + response['question'] + '?');
    var help_output = '<p>' + response['answer'] + '</p>';
    $("#main-display-div").html(help_output);
  } else {
   alert("Help answer not found");
  }
}

function Loading()
{
    $("#main h3").html('Loading');
    $("#main-display-div").html('<p><center><img src="../media/loader.gif" /></center></p>');
}

function LoadSubjectLeaf(subject)
{
  var data_obj = new Object();
  data_obj['func'] = 'getEndeavorsBySubject';
  data_obj['args'] = [subject];
  $.ajax({
    url: '/jquery',
	data: data_obj,
	type: 'POST',
	dataType: 'json',
	timeout: 100000,
	global: false,
	error: function(error,status) {
	  alert("Error loading subjects-tree " + error + ' Status:' + status);
	},
	success: function(json) {
	  var html_str = '<ul><li class="closed"><span class="folder">' + subject.toUpperCase() + ' (' +  json.length + ')';
	  html_str += '<sup><a href="#" onclick="DisplayCollection(\'' + subject.toUpperCase() + '\')">more</a></sup></span>';
	  for(var obj in json)
	  { 
		var endeavor = json[obj];
		html_str += '<ul><li class="closed"><span class="folder"><a href="' + endeavor['url'] + '" target="_top" ';
		html_str += ' onclick="add_use(\'' + endeavor['key'] + '\')">' + endeavor['title'] + '</a><sup>';
		html_str += '<a href="#" onclick="DisplayEndeavor(\'' + endeavor['key'] + '\')">?</a></sup></span>'
		html_str += '<ul><li class="closed"><div class="record_display">' + endeavor['description'] + '</div></li></ul>';
		html_str += '</li></ul>';
	  }
	  var branch = $(html_str).appendTo('#subjects-tree');
	  $('#subjects-tree').treeview({add:branch});
	}
  });

}

function LoadTitleLeaf(letter)
{
  var data_obj = new Object();
  data_obj['func'] = 'getEndeavorsByTitles';
  data_obj['args'] = [letter];
  $.ajax({
	   url: '/jquery',
	   data: data_obj,
	   type: 'POST',
	   dataType: 'json',
	   timeout: 100000,
	   global: false,
	   error: function(error,status) {
	       alert("Error loading titles-tree " + error + ' Status:' + status);
	   },
	   success: function(json) {
	     var html_str = '<ul><li class="closed"><span class="folder">' + letter.toUpperCase() + " (" + json.length + ")</span>";
		 html_str += '<sup><a href="#" onclick="DisplayCollection(' + letter + ')">more</a></sup></span><ul>';
	     for(var obj in json)
		 { 
		   var endeavor = json[obj];
		   html_str += '<li class="closed"><span class="folder"><a href="' + endeavor['url'] + '" target="_top" ';
		   html_str += ' onclick="add_use(\'' + endeavor['key'] + '\')">' + endeavor['title'] + '</a><sup>';
		   html_str += '<a href="#" onclick="DisplayEndeavor(\'' + endeavor['key'] + '\')">?</a></sup></span>'
		   html_str += '<ul><li class="closed"><div class="record_display">' + endeavor['description'] + '</div></li></ul>';
		   html_str += '</li>';
		 }
		 html_str += '</ul></li></ul>';
	     var branch = $(html_str).appendTo('#titles-tree');
	     //$(ul_id).html(html_str);
	     $('#titles-tree').treeview({add:branch});
	   }
	});

}

function LoadTrees(entity)
{
   LoadTitleLeaf('a');
   LoadSubjectLeaf('accounting');
   LoadSubjectLeaf('anthropology');
   LoadSubjectLeaf('art');
   LoadTitleLeaf('b');
   LoadSubjectLeaf('biology');
   LoadSubjectLeaf('business');
   LoadTitleLeaf('c');
   LoadSubjectLeaf('chemistry');
   LoadSubjectLeaf('communication');
   LoadSubjectLeaf('computer science');
   LoadTitleLeaf('d');
   LoadTitleLeaf('e');
   LoadSubjectLeaf('economics');
   LoadSubjectLeaf('education');
   LoadSubjectLeaf('english');
   LoadSubjectLeaf('exercise and sport science');
   LoadTitleLeaf('f');
   LoadTitleLeaf('g');
   LoadSubjectLeaf('geography');
   LoadSubjectLeaf('geology');
   LoadTitleLeaf('h');
   LoadSubjectLeaf('history');
   LoadTitleLeaf('i');
   LoadTitleLeaf('j');
   LoadSubjectLeaf('journalism');
   LoadTitleLeaf('k');
   LoadTitleLeaf('l');
   LoadSubjectLeaf('literature');
   LoadTitleLeaf('m');
   LoadSubjectLeaf('mathematics');
   LoadSubjectLeaf('music');
   LoadTitleLeaf('n');
   LoadTitleLeaf('o');
   LoadSubjectLeaf('outdoor leadership and resort management');
   LoadTitleLeaf('p');
   LoadSubjectLeaf('physics');
   LoadSubjectLeaf('political science');
   LoadSubjectLeaf('psychology');
   LoadTitleLeaf('q');
   LoadTitleLeaf('r');
   LoadTitleLeaf('s');
   LoadSubjectLeaf('sociology');
   LoadTitleLeaf('t');
   LoadSubjectLeaf('theatre');
   LoadTitleLeaf('u');
   LoadTitleLeaf('v');
   LoadTitleLeaf('w');
   LoadTitleLeaf('x');
   LoadTitleLeaf('y');
   LoadTitleLeaf('z');
   
   
}

function LoadRemainingTitles(letters)
{
  for(var i=0;i < letters.length;i++)
  {
    var letter = letters[i];
	server.getEndeavorsByAlpha(letter,LoadTitlesSuccess);
  }
}

function LoadEndeavors(endeavors)
{
  var branches = '';
  for(var i=0;i<endeavors.length;i++)
  {
	var endeavor = endeavors[i];
	branches += GenerateSubTree(endeavor);
   }
   return branches;
}

function LoadConceptsSuccess(response)
{
  if(response)
  {
    var raw_branches = '';
	var concepts = response['concepts'];
	for(var i=0;i<concepts.length;i++)
	{
	  var subject = concepts[i];
	  raw_branches += '<ul><li class="closed"><span class="folder">' + subject['display_form'] + ' (';
	  raw_branches += subject['resources'].length + ')<sup><a href="#" onclick="DisplayCollection(\'';
	  raw_branches += subject['display_form'] + '\')">more</a></sup></span><ul>';
	  raw_branches += LoadEndeavors(subject['resources']) + '</ul></li></ul>';
	}
	$("#subjects-tree").html(raw_branches);
    $("#subjects-tree").treeview();
  } else {
    alert("Error in loading subjects");
  }
}

function LoadTitlesSuccess(response)
{
  if(response)
  {
    var raw_branches = LoadEndeavors(response['endeavors']);
	var branches = $(raw_branches).appendTo("#titles-tree");
	$("#titles-tree").treeview({
	  add:branches
	});
  } else {
    alert("Error in loading titles");
  }
}

function Search()
{
  $("#popular-div").css("visibility", "hidden");
  $("#subjects-div").css("visibility", "hidden");
  $("#titles-div").css("visibility", "hidden");
  Loading();
  var search_terms = $("#search_terms").attr('value');
  var search_type = $("input[name='sitesearch']:checked").attr('value');
  switch(search_type)
  {
    case "all":
	  alert("Not implemented, waiting for Marmot Serials Solution 360 Federated Searching");
	  break;

	case "catalog":
	   top.location.href = 'http://www.millennium.marmot.org/search~S33/a?searchtype=Y&searcharg=' + search_terms;
	   break;

    case "elibrary":
	  server.search(search_terms,SearchResults);
	  break;

	default:
	  server.search(search_terms,SearchResults);
	  break;
  }
}

function SearchResults(response)
{
  if(response)
  {
    var search_terms = $("#search_terms").attr('value');
    $("#main h3").html('Search ' + response['endeavors'].length + ' Results for <i>' + search_terms + '</i>');
	var output = '';
	if(response['endeavors'].length > 0){
		for(var i=0;i<response['endeavors'].length;i++)
		{
		  var endeavor = response['endeavors'][i];
		  output += GenerateRecordDisplay(endeavor);
		}
	} else {
	   output = search_terms + " not found in E-Library.";
    }
	var regex = "/" + search_terms + "/gi";
	output.replace(regex,'<span class="search-term">' + search_terms + '</span>');
	$("#main-display-div").html(output);
	$("#main-display-div").highlight(search_terms);
  } else {
    alert("No response");
  }

}

